<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/11/4
 * Time: 14:10
 */

namespace Common\Api;


use Admin\Api\OrdersPaycodeApi;
use Admin\Api\UidMgroupApi;
use Common\ConstVar\BoyeActionConstModel;
use Shop\Api\MemberConfigApi;
use Shop\Api\OrdersApi;
use Shop\Api\OrdersItemApi;
use Shop\Api\OrderStatusApi;
use Shop\Api\ProductQuantityHisApi;
use Shop\Api\ProductSkuApi;
use Shop\Api\RedEnvelopeApi;
use Shop\Api\WalletApi;
use Ucenter\Api\MemberExpApi;

class PayOrderApi {
    //支付成功时
    const SUCCESS = "Common/PayOrder/success";

    public function success($out_trade_nos,$pay_type){

        addLog("PayOrder/success",$out_trade_nos,$out_trade_nos,"1.PayOrderApi SUCCESS!");
        $p_pos = strpos($out_trade_nos,"P");
        $pay_id = substr($out_trade_nos,$p_pos+1,strlen($out_trade_nos)-$p_pos);

        $map=array(
            'id'=>$pay_id
        );
        $result = apiCall(OrdersPaycodeApi::GET_INFO,array($map));
        $u_pos  = strpos($out_trade_nos,"U");
        $uid    = substr($out_trade_nos,$u_pos+1,$p_pos-$u_pos-1);

        addLog("AlipayApp/notify_url",$uid.'_'.$pay_id,$result,"获取支付编号对应的订单编号"."3.支付异步通知[PC]!");
        //2. 支付成功后更新订单状态
        if($result['status'] && is_array($result['info'])){

            $orderCodeArray=explode(';',$result['info']['order_content']);

            foreach($orderCodeArray as $order_code){
                if(empty($order_code)){
                    continue;
                }

                addLog("AlipayApp/notify_url",$uid,$result,"修改订单支付状态"."4.支付异步通知[PC]!");
                $result = apiCall(OrderStatusApi::PAY_ORDER,array($out_trade_nos,$order_code,$uid,$pay_type));

                if(!$result['status']){
                    LogRecord($result['info'],__FILE__.__LINE__);
                    continue;
                }

                //TODO:
                // 1. 计算返佣
                // 2. 统计成交笔数,对用户级别进行升级
                // 3. 发送通知给用户？
                // 4. 减库存？
                // 5.

                $result = apiCall(OrdersApi::GET_INFO,array(array('order_code'=>$order_code)));
                if(!$result['status']){
                    LogRecord($result['info'],__FILE__.__LINE__);
                    return;
                }
                $order_info = $result['info'];
                if(is_null($order_info)){
                    continue;
                }

                // 1. 用户经验+1
                //action_log(BoyeActionConstModel::PAY_SUCCESS,"member_config",$uid,$uid);

                // 2. 更新用户组
                //$this->updateMemberGroup($order_info,$uid);

                // 3. 返佣的计算
                //$this->calCommission($order_info,$uid);

                // 1. 注册用户购买即返回实际支付的10%的购物券
                $this->sendShoppingEnvelope($uid,$order_info['price']);

                // 2. 购物消费: 消费的金额＝经验
                $result = apiCall(MemberExpApi::EXP_INC,array($uid,$order_info['price']));
                if(!$result['status']){
                    LogRecord($result['info'],__FILE__.__LINE__);
                }

                // 3. 库存变动
                $map = array(
                    'order_code' => $order_code,
                );
                $result = apiCall(OrdersItemApi::QUERY_NO_PAGING,array($map));
                if($result['status']){
                    $data = array();
                    foreach($result['info'] as $k => $v){
                        $map = array(
                            'product_id' => $v['p_id'],
                            'sku_id' => $v['sku_id'],
                        );
                        $res = apiCall(ProductSkuApi::GET_INFO,array($map));
                        if(!$res['status']){
                            return ;
                        }
                        $quantity = $res['info']['quantity'];
                        $data[$k] = array(
                            'change' => (-1)*$v['count'],
                            'pid' => $v['p_id'],
                            'create_time' => time(),
                            'change_time' => time(),
                            'operator_uid' => 0,
                            'operator_name' => '系统',
                            'notes' => '售出',
                            'sku_id' => $v['sku_id'],
                            'left_quantity' => $quantity - $v['count'],
                            'dtree_type' => 6076,
                        );
                    }
                    $result = apiCall(ProductQuantityHisApi::ADD_ALL,array($data));
                    if(!$result['status']){
                        LogRecord($result['info'],__FILE__.__LINE__);
                    }
                }else{
                    LogRecord($result['info'],__FILE__.__LINE__);
                }

            }
            return 0;
        }

        return -2;
    }

    /**
     * 计算返佣金额
     * @param $order_info
     * @param $uid
     */
    private function calCommission($order_info,$uid){
        //不含税
        $goodsAmount = floatval($order_info['goods_amount']);
        $discountMoney = floatval($order_info['discount_money']);
        $brokerageRatio = $order_info['brokerage_ratio'];
        addLog("PayOrderApi/calCommission",$goodsAmount,$discountMoney,"[调试]支付成功后!",true);

        $commission_price = round($brokerageRatio * ($goodsAmount - $discountMoney),2);
        $idcode = $order_info['idcode'];
        $result = apiCall(MemberConfigApi::GET_INFO,array(array('idcode'=>$idcode)));
        if($result['status'] && is_array($result['info'])){

            $result = apiCall(WalletApi::PLUS,array($uid,$commission_price,getDatatree('COMMISSION_ORDER_PAID'),"订单".$order_info['order_code']."返佣".$commission_price."元"));
            if(!$result['status']){
                LogRecord("增加返佣金额失败!",__FILE__.__LINE__);
            }

        }else{
            LogRecord("计算返佣时获取返佣对象的用户信息失败!",__FILE__.__LINE__);
        }
    }

    private function updateMemberGroup($order_info,$uid){

        $store_id = $order_info['storeid'];

        $result = apiCall(UidMgroupApi::UPDATE_GROUP,array($uid,$store_id));
        if($result['status']){
            //1. 成功升级
            action_log(BoyeActionConstModel::M_GROUP_LEVEL_UP,"member_config",$uid,$uid);
        }

    }

    /**
     * 注册用户购买即返回实际支付的10%的购物券
     */
    private function sendShoppingEnvelope($uid,$total_price){

        $result = apiCall(RedEnvelopeApi::SEND_SHOPPING_ENVOLOPE,array($uid,$total_price));

        if(!$result['status']){
            LogRecord("购物返红包失败!",__FILE__.__LINE__);
        }

    }
}